package com.linqi.freebie.base

import kotlinx.coroutines.*
import moe.tlaster.precompose.viewmodel.ViewModel

open class BaseViewModel : ViewModel() {

    // 使用 SupervisorJob 来避免子协程失败导致全部失败
    private val job = SupervisorJob()
    protected val viewModelScope = CoroutineScope(Dispatchers.Main + job)

    /**
     * 在主线程(UI)中执行协程
     */
    protected fun launchOnUI(block: suspend CoroutineScope.() -> Unit): Job {
        return viewModelScope.launch(Dispatchers.Main) { block() }
    }

    /**
     * 在IO线程中执行协程
     */
    protected fun launchOnIO(block: suspend CoroutineScope.() -> Unit): Job {
        return viewModelScope.launch(Dispatchers.IO) { block() }
    }

    override fun onCleared() {
        super.onCleared()
        job.cancel() // 释放协程
    }
}
